import React from 'react';
import { Navigate } from 'react-router-dom';

interface RoleProtectedRouteProps {
    children: React.ReactNode;
    allowedRoles: string[];
}

const RoleProtectedRoute: React.FC<RoleProtectedRouteProps> = ({ children, allowedRoles }) => {
    const getUserInfo = () => {
        try {
            const userStr = localStorage.getItem('user');
            return userStr ? JSON.parse(userStr) : null;
        } catch (error) {
            console.error('获取用户信息失败:', error);
            return null;
        }
    };

    const user = getUserInfo();
    const userRole = user?.role || '';

    // 如果没有角色或角色不在允许列表中，重定向到首页
    if (!userRole || !allowedRoles.includes(userRole)) {
        return <Navigate to="/admin/home" replace />;
    }

    return <>{children}</>;
};

export default RoleProtectedRoute;

